﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Dan.Common
{
    public class RequestInfo
    {
        /// <summary>
        /// Gets or sets the server URL.
        /// </summary>
        /// <value>
        /// The server URL.
        /// </value>
        public static string ServerUrl { get; set; }

        /// <summary>
        /// 当前url(去除?后面的参数)
        /// </summary>
        public string Path { get; set; }

        /// <summary>
        /// ?后面参数
        /// </summary>
        public string Query { get; set; }

        /// <summary>
        /// Form 信息
        /// </summary>
        public string FormData { get; set; }

        /// <summary>
        /// header 信息
        /// </summary>
        public string Header { get; set; }

        public Exception Exception { get; set; }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }

        #region static method

        /// <summary>
        /// Gets the query string.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public static string GetQueryStr(HttpRequest request)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine();
            var index = 0;
            foreach (var key in request.Query.Keys)
            {
                if (index == 0)
                {
                    sb.Append($"?{key}={request.Query[key]}");
                }
                else
                {
                    sb.Append($"&{key}={request.Query[key]}");
                }

                index++;
            }

            return sb.ToString();
        }

        /// <summary>
        /// Gets the form string.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public static string GetFormStr(HttpRequest request)

        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine();
            foreach (var item in request.Form)
            {
                sb.Append($"{item.Key} : {item.Value}\r\n");
            }

            return sb.ToString();
        }

        /// <summary>
        /// Gets the header string.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public static string GetHeaderStr(HttpRequest request)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in request.Headers)
            {
                sb.Append($"{item.Key} : {item.Value}\r\n");
            }

            return sb.ToString();
        }

        #endregion
    }
}